package server.handler;

import java.awt.AWTException;
import java.awt.Robot;
import java.io.IOException;
import java.util.concurrent.LinkedBlockingQueue;

import server.command.Command;
import server.command.MarkCommand;

public class CommandManager implements Runnable {

	private LinkedBlockingQueue<Command> commands;
	private CommandReceiver receiver;

	private CommandHandler handler;
	private ActionCommandHandler aHandler;
	private MarkCommandHandler mHandler;
	private Robot robot;

	public CommandManager() throws IOException {
		try {
			this.robot = new Robot();
		} catch (AWTException e) {
			e.printStackTrace();
		}

		this.receiver = new CommandReceiver();
		this.commands = this.receiver.getCommands();
		this.aHandler = new ActionCommandHandler(this.robot);
		this.mHandler = new MarkCommandHandler(this.robot);
	}

	@Override
	public void run() {
		new Thread(this.receiver).start();
		try {
			while (true) {
				Command command = this.commands.take();
				if (MarkCommand.isMarkCommand(command)) {
					handler = mHandler;
				} else {
					handler = aHandler;
				}
				handler.handle(command);
			}
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
}
